<template>
  <qui-page :data-qui-theme="theme" class="qui-at-member-page-box">
    <view class="qui-at-member-page-box__hd">
      <view class="qui-at-member-page-box__hd__sc">
        <qui-icon class="icon-search" name="icon-search" size="30"></qui-icon>
        <input type="text" placeholder-class="input-placeholder" confirm-type="search" :placeholder="
            select === 'select'
              ? i18n.t('discuzq.atMember.selectUser')
              : i18n.t('discuzq.atMember.selectedMember')
          " @input="searchInput" />
      </view>
    </view>
    <view class="qui-at-member-page-box__lst">
      <scroll-view class="scroll-Y" scroll-y="true" scroll-with-animation="true" @scrolltolower="lower"
        :style="select !== 'select' ? 'height:calc(100vh - 292rpx)' : 'height:calc(100vh - 2rpx)'">
        <checkbox-group @change="changeCheck" v-if="followStatus && select !== 'select'">
          <label v-for="item in allFollow" :key="item.id">
            <qui-avatar-cell v-if="item.toUser" :mark="item.toUser.id" :title="item.toUser.username"
              :icon="item.toUser.avatarUrl ? item.toUser.avatarUrl : 'https://www.qiyaoshuizu.cn/static/noavatar.gif'"

              :value="(Object.values(item.toUser.groups)).length > 0 ? (Object.values(item.toUser.groups))[0].name : ''" :label="item.toUser.label"
              :is-real="item.toUser.isReal">
              <checkbox slot="rightIcon" :value="JSON.stringify(item)"></checkbox>
            </qui-avatar-cell>
          </label>
        </checkbox-group>
        <checkbox-group @change="changeCheck" v-if="!followStatus && select !== 'select'">
          <label v-for="item in allSiteUser" :key="item.id" @tap="radioChange(item)">
            <qui-avatar-cell :mark="item.id" :title="item.username"
              :icon="item.avatarUrl ? item.avatarUrl : 'https://www.qiyaoshuizu.cn/static/noavatar.gif'"
              :value="getGroups(item.groups)" :label="item.label" :is-real="item.isReal">
              <checkbox slot="rightIcon" :value="JSON.stringify(item)"></checkbox>
            </qui-avatar-cell>
          </label>
        </checkbox-group>
        <!-- <view v-if="select === 'select' && followStatus">
          <view v-for="item in allSiteUser" :key="item.id">
            <qui-avatar-cell
              :mark="item.id"
              :title="item.username"
              :icon="item.avatarUrl ? item.avatarUrl : '/static/noavatar.gif'"
              :value="item.groups[0].name"
              :label="item.label"
              :is-real="item.isReal"
              @click="radioChange(item)"
            ></qui-avatar-cell>
          </view>
        </view> -->
        <view v-if="select === 'select'">
          <view v-for="item in allSiteUser" :key="item.id" @tap="radioChange(item)">
            <qui-avatar-cell :mark="item.id" :title="item.username"
              :icon="item.avatarUrl ? item.avatarUrl : 'https://www.qiyaoshuizu.cn/static/noavatar.gif'" :value="getGroups(item.groups)"
              :label="item.label" :is-real="item.isReal" ></qui-avatar-cell>
          </view>
        </view>
        <view class="loading-text">
          <qui-icon v-if="
              loadingText === 'search.norelatedusersfound' || loadingText === 'search.noFollowers'
            " name="icon-noData"></qui-icon>
          <text class="loading-text__cont">{{ i18n.t(loadingText) }}</text>
        </view>
      </scroll-view>
    </view>
    <view class="qui-at-member-page-box__ft" v-if="select !== 'select'">

    </view>
  </qui-page>
</template>

<script>
  import {
    mapMutations
  } from 'vuex';

  export default {
    name: 'QuiAtMemberPage',
    data() {
      return {
        allSiteUser: [], // 所有站点成员
        allFollow: [], // 所有关注成员
        followStatus: true, // 第一次进来显示follow列表
        checkAvatar: [], // 选择人员列表
        loadingText: 'discuzq.list.loading',
        searchValue: '', // 搜索值
        pageNum: 1, // 页面
        meta: {}, // 接口返回meta值
        select: true, // 选择被提问人
        current: 0,
        categoryId: 0,
        categoryIndex: 0,
      };
    },
    methods: {
      ...mapMutations({
        setAtMember: 'atMember/SET_ATMEMBER',
      }),
      handleGroups(data) {
        let groups = [];
        if (data.groups && data.groups.length > 0) {
          groups = data.groups.filter(item => item.isDisplay);
        }
        if (groups.length > 0) {
          return groups[0].name;
        }
        return '';
      },
      // 多选人员
      changeCheck(e) {
        this.checkAvatar = [];
        e.detail.value.forEach(item => {
          if (this.followStatus) {
            this.checkAvatar.push(JSON.parse(item).toUser);
          } else {
            this.checkAvatar.push(JSON.parse(item));
          }
        });
        this.getCheckMember()
      },
      // 单选人员
      radioChange(item) {
         uni.navigateTo({
          url: `/topic/post?type=5&categoryId=${this.categoryId}&categoryIndex=${this.categoryIndex}`, // &lowestPrice=${item.canBeAskedMoney}
        });
        setTimeout(() => {
          console.log('item',item)
          if (item.toUser) {
            uni.$emit('radioChange', item.toUser);
          } else {
            uni.$emit('radioChange', item);
          }
        }, 1000);
      },
      getCheckMember() {
        this.setAtMember(this.checkAvatar);
        uni.navigateBack({
          delta: 1,
        });
      },
      // 人员搜索
      searchInput(e) {
        this.followStatus = false;
        this.searchValue = e.detail.value;
        this.checkAvatar = [];

        if (this.pageNum !== 1) {
          this.pageNum = 1;
        }

        this.loadingText = 'discuzq.list.loading';

        if (this.timeout) clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          this.allSiteUser = [];
          this.getSiteMember(1);
        }, 250);
      },
      // 上划加载更多
      lower() {
        if (this.followStatus) {
          if (this.meta.total > this.allFollow.length) {
            this.pageNum += 1;
            this.getFollowMember(this.pageNum);
          } else {
            this.loadingText = 'discuzq.list.noMoreData';
          }
        } else if (this.meta.total > this.allSiteUser.length) {
          this.pageNum += 1;
          this.getSiteMember(this.pageNum);
        } else {
          this.loadingText = 'discuzq.list.noMoreData';
        }
      },

      // 接口请求
      getFollowMember(number) {
        const params = {
          include: ['toUser', 'toUser.groups'],
          'page[size]': 20,
          'page[number]': number,
        };
        if (this.select === 'select') {
          params['filter[canBeAsked]'] = 'yes';
        }
        this.$store.dispatch('jv/get', ['follow', {
          params
        }]).then(res => {
           /* eslint no-underscore-dangle: ["error", { "allow": ["_jv"] }] */
          this.meta = res._jv.json.meta;
          let data = Object.values(res)
          this.allFollow = [...this.allFollow, ...data];
          if (this.meta.total === 0) {
            this.loadingText = 'search.norelatedusersfound';
          } else if (this.meta.total <= 20) {
            this.loadingText = 'discuzq.list.noMoreData';
          }
        });
      },
      getSiteMember(number) {
        const params = {
          'filter[username]': `*${this.searchValue}*`,
          'filter[status]': 'normal',
          'page[size]': 20,
          'page[number]': number,
        };
        if (this.select === 'select') {
          params['filter[canBeAsked]'] = 'yes';
        }
        this.$store.dispatch('jv/get', ['users', {
          params
        }]).then(res => {
           this.meta = res._jv.json.meta;

          let data =Object.values(res);
          this.allSiteUser = [...this.allSiteUser, ...data];
          if (data.length === 0) {
            this.loadingText = 'search.norelatedusersfound';
          } else if (res._jv.json.meta.total <= 20 && data.length!== 0) {
            this.loadingText = 'discuzq.list.noMoreData';
          }
        });
      },
      getGroups(groups){
        if(groups)
        {
        let g=Object.values(groups);
        if(g.length>0)
        {
          return g[0].name;
        }
        }

      },
      // 点击头像调转到个人主页
      headClick(id) {
        if (!id || id <= 0) {
          return;
        }
        uni.navigateTo({
          url: `/pages/profile/index?userId=${id}`,
        });
      },
    },
    onLoad(option) {
      this.select = option.name;
      this.categoryId = option.categoryId;
      this.categoryIndex = option.categoryIndex;
      if (option.name === 'select') {
        this.followStatus = false;
        uni.setNavigationBarTitle({
          title: this.i18n.t('discuzq.atMember.selectUser'),
        });
      } else {
        uni.setNavigationBarTitle({
          title: this.i18n.t('discuzq.atMember.atTitle'),
        });
      }
      if (option.name !== 'select') {
        this.getFollowMember(1);
      } else if (option.name === 'select') {
        this.getSiteMember(1);
      }
      this.setAtMember([]);
    },
  };
</script>

<style lang="scss" scoped>
  @import '@/styles/base/theme/fn.scss';
  @import '@/styles/base/variable/global.scss';

  $otherHeight: 292rpx;

  .qui-at-member-page-box {
    width: 100%;
    height: 100%;
    padding-top: 60rpx;
    background-color: --color(--qui-BG-2);

    &__hd {
      display: flex;
      align-items: center;
      height: 80rpx;
      padding: 20rpx 40rpx;

      &__sc {
        display: flex;
        align-items: center;
        width: 100%;
        height: 100%;
        padding: 0 10rpx;
        background-color: --color(--qui-BG-IT);
        border-radius: 7rpx;

        border-radius: 80rpx;


        .icon-search {
          margin: 0 10rpx;
          color: #bbb;
        }

        input {
          width: 100%;
          height: 100%;
        }

        /deep/ input .input-placeholder {
          font-size: $fg-f4;
          color: --color(--qui-FC-C6);
        }
      }
    }

    &__lst {
      .scroll-Y {

        // height: calc(100vh - #{$otherHeight});
        .loading-text {
          height: 100rpx;
          font-size: 28rpx;
          line-height: 100rpx;
          color: --color(--qui-FC-AAA);
          text-align: center;
        }

        .loading-text__cont {
          margin-left: 20rpx;
        }
      }
    }

    &__ft {
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 40rpx;
      background-color: --color(--qui-BG-2);
      box-sizing: border-box;

      /deep/ .qui-button--button[size='large'] {
        border-radius: 5rpx;
      }

      /deep/ .qui-button--button[disabled] {
        color: #7d7979;
        background-color: #fff;
      }
    }
  }
</style>
